//
//  ChatBar.m
//  keyboard
//
//  Created by 遇水 on 16/3/12.
//  Copyright © 2016年 遇水. All rights reserved.
//

#import "ChatBar.h"
#import "ChatBarFaceView.h"
#import "ChatBarMoreView.h"
#import "Masonry.h"
#import "UIView+Extension.h"
#import "Utiles.h"
#import "FaceModel.h"
#import "ImageManager.h"
#import "FileManager.h"
//先实现各种文字编辑的吧

/**导入MoreViewSubViewController*/
#import "UserLocationViewController.h"
#import "VedioingViewController.h"
#import "VoiceingViewController.h"


@interface ChatBar ()<ChatBarMoreViewDelegate,ChatBarMoreViewDatasource, UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate, VoiceingViewControllerDelegate,VedioingViewControllerDelegate>

/**录音按钮*/
@property (strong, nonatomic) UIButton *voiceButton;
/**表情按钮*/
@property (strong, nonatomic) UIButton *faceButton;
/**更多按钮*/
@property (strong, nonatomic) UIButton *moreButton;
/**开始录音按钮*/
@property (nonatomic, strong) UIButton    *voiceingButton;
/**表情键盘*/
@property (nonatomic, strong) ChatBarFaceView    *faceView;
/**更多键盘*/
@property (nonatomic, strong) ChatBarMoreView    *moreView;
/**输入框*/
@property (strong, nonatomic) UITextView *textView;     //输入框

//考虑表情键盘和更多键盘是否使用懒加载方式实现

//@property (nonatomic, assign) BOOL    switchKeyboarding;

@property (nonatomic, strong) NSString    *textViewText;

@property (nonatomic, strong) UIButton    *selectedButton;      //当前选中的按钮

//标记是否正在添加表情图片中
@property (nonatomic, assign) BOOL    isAddCustomFaceing;

@end


@implementation ChatBar


-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.chatBarHeight = 45;
        //设置默认的位置
        self.superViewController = [self keyWindowRootViewController];
        [self initSubview];
        [self regesterNotification];

    }
    
    return self;
}

-(void)setChatBarHeight:(CGFloat)chatBarHeight
{
    _chatBarHeight = chatBarHeight;
}

-(void)initSubview
{
    //上边的分割线
    UIView *headLine = [UIView new];
    [headLine setBackgroundColor:[UIColor grayColor]];
    [self addSubview:headLine];
    
    __block __typeof(self) weakSelf = self;
    [headLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(weakSelf);
        make.height.equalTo(@0.5f);
    }];
    
    
    //初始化录音按钮
    UIButton *voiceButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [voiceButton setImage:[UIImage imageNamed:@"chat_bar_voice_normal"] forState:UIControlStateNormal];
     [voiceButton setImage:[UIImage imageNamed:@"chat_bar_input_normal"] forState:UIControlStateSelected];
    [voiceButton addTarget:self action:@selector(voiceButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [voiceButton sizeToFit];
    [self addSubview:voiceButton];
    self.voiceButton = voiceButton;
    
    
    [voiceButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf);
        make.left.equalTo(weakSelf).offset(10);
    }];
    
    //初始化输入框
    UITextView *textView = [[UITextView alloc]init];
    textView.delegate = self;
    textView.layer.cornerRadius = 5.0f;
    textView.returnKeyType = UIReturnKeySend;
    textView.font = [UIFont systemFontOfSize:15.0f];
    textView.layer.borderWidth = 0.5f;
    textView.layer.masksToBounds = YES;
    textView.layer.borderColor = [UIColor grayColor].CGColor;
    
    [self addSubview:textView];
    self.textView = textView;
    
    //初始化图像按钮
    UIButton *faceButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [faceButton setBackgroundImage:[UIImage imageNamed:@"chat_bar_face_normal"] forState:UIControlStateNormal];
    [faceButton setBackgroundImage:[UIImage imageNamed:@"chat_bar_input_normal"] forState:UIControlStateSelected];
    [faceButton addTarget:self action:@selector(faceButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [faceButton sizeToFit];
    
    [self addSubview:faceButton];
    self.faceButton  = faceButton;
    
    //初始化更多按钮
    UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [moreButton setBackgroundImage:[UIImage imageNamed:@"chat_bar_more_normal"] forState:UIControlStateNormal];;
    [moreButton setBackgroundImage:[UIImage imageNamed:@"chat_bar_input_normal"] forState:UIControlStateSelected];
    [moreButton addTarget:self action:@selector(moreButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [moreButton sizeToFit];
    
    [self addSubview:moreButton];
    self.moreButton = moreButton;
    
    [moreButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf);
        make.right.equalTo(weakSelf).offset(-5);
    }];
    
    [faceButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf);
        make.right.equalTo(moreButton.mas_left).offset(-5);
    }];
    
    
    [textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf).offset(5);
        make.bottom.equalTo(weakSelf).offset(-5);
        make.centerY.equalTo(weakSelf);
        make.left.equalTo(voiceButton.mas_right).offset(5);
        make.right.equalTo(faceButton.mas_left).offset(-5);
    }];
    
    
    
    self.selectedButton = self.faceButton;

}

//注册通知
-(void)regesterNotification
{
    //键盘改变
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];

    //发送消息通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(chatBarFaceViewButtomViewSendMessage:) name:NotificationSendMessage object:nil];
    
    //表情通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(selectedFaceNotification:) name:NotificationFace object:nil];
    
    //删除通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(deleteNotification) name:NotificationDelete object:nil];
    
    //添加自定义表情通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(addCustomFaceNotification) name:NotificationConstomAdd object:nil];

    //发送自定义表情通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(sendCustomFaceNotification:) name:NotificationConstomFace object:nil];
    
}


#pragma mark 通知事件
//选择Face后
-(void)selectedFaceNotification:(NSNotification *)notification
{
    FaceModel *model = notification.userInfo[Face];
    
    //添加进最近使用的
    [[FileManager sharedFileManager]saveFace:model];
    
    if (model.code) {
        //说明是emoji表情,将此内容传递给textView来显示
        [self.textView insertText:model.code.emoji];
    }
    
    if(model.png){
        //说明是图片表情
        UIImage *image = [UIImage imageNamed:model.png];
        
        NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc]init];
        [attrString appendAttributedString:self.textView.attributedText];       //将之前的内容拼接进来
        
        NSTextAttachment *textAttachment = [[NSTextAttachment alloc]init];
        textAttachment.image = image;
        CGFloat attachmentH = self.textView.font.lineHeight;
        textAttachment.bounds = CGRectMake(0, -5 , attachmentH, attachmentH);  //会偏移
        NSAttributedString *attributeString = [NSAttributedString attributedStringWithAttachment:textAttachment];
        
//        [attrString appendAttributedString:attributeString];    //此处是拼接到最后， 如何插入带有图片的字符串呢
        //插入到光标所在的位置
        NSUInteger location = self.textView.selectedRange.location;

        [attrString insertAttributedString:attributeString atIndex:location];
        
        
        [attrString addAttribute:NSFontAttributeName value:self.textView.font range:NSMakeRange(0, attrString.length)];
        
        
        self.textView.attributedText = attrString;
        
        //移动光标到表情后面
        self.textView.selectedRange = NSMakeRange(location + 1, 0);
        
        
    }
}


-(void)addCustomFaceNotification
{
    self.isAddCustomFaceing = YES;
    [self openAlbum];
    
}

-(void)sendCustomFaceNotification:(NSNotification *)notification
{
    NSDictionary *userInfo = notification.userInfo;
    FaceModel *model = userInfo[Face];
    NSString *urlS = model.urlString;
    
    //通过URL地址从本地相册库中获取文件   然后放松
    UIImage *image = [[ImageManager sharedImageManager]imageWithToPath:urlS];
    [self sendImage:@[image]];

    [[FileManager sharedFileManager]saveFace:model];
}


-(void)deleteNotification
{
    [self.textView deleteBackward];
}


-(void)chatBarFaceViewButtomViewSendMessage:(NSNotification *)notification
{
    [self sendTextMessage:self.textView.attributedText];
}


-(void)keyBoardChangeFrame:(NSNotification *)notification
{
   
//    if (self.switchKeyboarding) {
//        return;
//    }
//    
    NSDictionary *userInfo = notification.userInfo;
    //获得动画执行时间
    NSTimeInterval duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey]doubleValue];
    
    CGRect keyboardFrame = [userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];

    
    [UIView animateWithDuration:duration animations:^{
        if (self.superViewController ==nil) {
              self.superViewController = [self keyWindowRootViewController];
        }
        
        //工具条的Y = 键盘的y - 工具条的H   ， 成立说明键盘还没有出来
        if (keyboardFrame.origin.y > self.superViewController.view.height) {
            //设置自己的Y值
            self.y = self.superViewController.view.height - self.height;
        }else
        {
            //键盘已经弹出
            self.y = keyboardFrame.origin.y - self.height;
        }
    }];

}

#pragma mark buttonAction
-(void)voiceButtonAction:(UIButton *)button
{
    if (self.selectedButton != button) {
        self.selectedButton.selected  = NO;
        button.selected = YES;
        self.selectedButton =button;
        //显示录音键盘
        [self showKeyboard:KeyboardShowTypeVoice];
    }else{
        self.selectedButton = nil;
        button.selected = NO;
        //显示系统自带键盘
        [self showKeyboard:KeyboardShowTypeCustem];
    }

    
}

-(void)faceButtonAction:(UIButton *)button
{
    //说明当前按钮没有选中
    if (self.selectedButton != button) {
        self.selectedButton.selected  = NO;
        button.selected = YES;
        self.selectedButton =button;
        [self showKeyboard:KeyboardShowTypeFace];
        //显示表情键盘
    }else
    {
        self.selectedButton = nil;
        button.selected = NO;
        //显示系统自带键盘
//        NSLog(@"--------显示系统键盘");
        [self showKeyboard:KeyboardShowTypeCustem];
    }
}


-(void)moreButtonAction:(UIButton *)button
{
    if (self.selectedButton != button) {
        self.selectedButton.selected  = NO;
        button.selected = YES;
        self.selectedButton =button;
//        NSLog(@"---------显示更多键盘");
        [self showKeyboard:KeyboardShowTypeMore];
        //显示表情键盘
    }else
    {
        self.selectedButton = nil;
        button.selected = NO;
        //显示系统自带键盘
//        NSLog(@"--------显示系统键盘");
        [self showKeyboard:KeyboardShowTypeCustem];
    }
}



-(void)showKeyboard:(KeyboardShowType)type
{
    switch (type) {
        case KeyboardShowTypeFace:
        {
            //表情键盘
            [self showKeyboardTypeFace];
           break;
        }

        case KeyboardShowTypeMore:
        {
              //更多
            [self showKeyboarTypeMore];
            break;
        }
        case KeyboardShowTypeVoice:
        {
             //语音
            [self showKeyboardTypeVoice];
            break;
        }
        case KeyboardShowTypeCustem:
        {
             //默认
            [self showKeyboardTypeCustem];
            break;
        }
        case KeyboardShowTypeNothing:
        {
             //不显示键盘
            [self showKeyboardTypeNothing];
            break;
        }
    }
}


-(void)showKeyboardTypeFace
{
    if (self.textView.inputView != self.faceView) {
        self.textView.inputView = self.faceView;
    }
    
    
//    self.switchKeyboarding = YES;
    
    [self.textView endEditing:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.textView becomeFirstResponder];
        
//        self.switchKeyboarding = NO;
    });
}

-(void)showKeyboarTypeMore
{
    if (self.textView.inputView != self.moreView) {
            self.textView.inputView = self.moreView;;
    }

//    self.switchKeyboarding = YES;
    
    [self.textView endEditing:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.textView becomeFirstResponder];
        
//        self.switchKeyboarding = NO;
    });
}

/**
 *  切换为系统键盘
 */
-(void)showKeyboardTypeCustem
{
    if (self.textView.inputView != nil) {
        self.textView.inputView = nil;;
    }
    
    
    
//    self.switchKeyboarding = YES;
    
    [self.textView endEditing:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.textView becomeFirstResponder];
        
//        self.switchKeyboarding = NO;
    });
    
}


/**
 *  不显示键盘
 */
-(void)showKeyboardTypeNothing
{
    [self.textView endEditing:YES];
}



-(void)showKeyboardTypeVoice
{

    
    if ([self.textView isEditable]) {
        [self.textView endEditing:YES];
    }
    
    //添加录音按钮
    
}



-(void)endEdit
{
    //设置自己不处于编辑状态，收回所有的键盘
    [self endEditing:YES];
}


//如果没有设置superView 的话那么久根据系统根控制器来执行
-(ChatBarFaceView *)faceView
{
    if (!_faceView) {
        _faceView = [[ChatBarFaceView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 215)];
    }
    
    return _faceView;
}


-(ChatBarMoreView *)moreView
{
    if (!_moreView) {
        _moreView = [[ChatBarMoreView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 215)];
        _moreView.delegate = self;
        _moreView.dataSource =self;
    }
    
    return _moreView;
}


-(UIButton *)voiceingButton
{
    if (!_voiceingButton) {
        _voiceingButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _voiceingButton.frame = self.textView.bounds;
        //默认是隐藏的
        _voiceingButton.hidden = YES;
        [_voiceingButton setTitle:@"按住开始录音" forState:UIControlStateNormal];
        
    }
    return _voiceingButton;
}

//是否显示录音按钮
-(void)isShowVoiceingButton:(BOOL)isShow
{
   
}




#pragma mark - ChatBarMoreViewDelegate
-(NSArray<ChatBarMoreViewItemModel *> *)moreViewOfDataSource:(ChatBarMoreView *)moreView
{
    NSArray *titles = @[@"拍摄",@"照片",@"位置",@"视频", @"视频聊天", @"语音聊天"];
    NSArray *images = @[@"chat_bar_icons_camera",@"chat_bar_icons_pic",@"chat_bar_icons_location"];
//    NSArray *type = @[ChatBarMoreViewItemTypeCamera,ChatBarMoreViewItemTypeAlbum, ChatBarMoreViewItemTypeLocation];
    
    NSMutableArray *array = [[NSMutableArray alloc]init];
    for (NSInteger i = 0; i < titles.count; i++) {
        ChatBarMoreViewItemModel *model = [[ChatBarMoreViewItemModel alloc]init];
        model.title = titles[i];
        if(i < images.count){
            model.imageName = images[i];
        }else{
            NSLog(@"-------没有图片，请添加对应的图片");
        }
        
        model.type = i;
        
        [array addObject:model];
    }

    
    return array;
}


-(void)chatBarMoreView:(ChatBarMoreView *)chatBarMoreView didSelectedAtIndex:(ChatBarMoreViewItemType)type
{
    switch (type) {
        case ChatBarMoreViewItemTypeCamera: {
            [self openCamera];
            break;
        }
        case ChatBarMoreViewItemTypeAlbum: {
            [self openAlbum];
            break;
        }
        case ChatBarMoreViewItemTypeLocation: {
            [self openLocation];
            break;
        }
        case ChatBarMoreViewItemTypeVedio:{
            [self openVedio];
            break;
        }
        case ChatBarMoreViewItemTypeVeidoing:{
            [self openVedioing];
            break;
        }
        case ChatBarMoreViewItemTypeVoiceing:{
            [self openVoiceing];
            break;
        }
    }
}
#pragma mark 私有方法

-(void)openCamera
{
    UIImagePickerController *imagePieckerVC  =[[UIImagePickerController alloc]init];
    imagePieckerVC.delegate = self;
    imagePieckerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    //从哪个控制器弹出呢
    [self.superViewController presentViewController:imagePieckerVC animated:YES completion:nil];
}

-(void)openAlbum
{
    UIImagePickerController *imagePickerVC = [[UIImagePickerController alloc]init];
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        //提示用户
    }
    imagePickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePickerVC.delegate = self;
    [self.superViewController presentViewController:imagePickerVC animated:YES completion:nil];
    //弹出
}

-(void)openVedio
{
    UIImagePickerController *imagePickerVC  = [[UIImagePickerController alloc]init];
    imagePickerVC.delegate = self;
    imagePickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
    //设置为后置摄像头
    imagePickerVC.mediaTypes = @[(NSString *)kUTTypeVideo];         //这句代码导致程序崩溃Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'No available types for source 1'
    imagePickerVC.cameraDevice = UIImagePickerControllerCameraDeviceRear;
    imagePickerVC.videoQuality = UIImagePickerControllerQualityTypeIFrame1280x720;
    //设置摄像头模型为录像视频
    imagePickerVC.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
    
    [self.superViewController presentViewController:imagePickerVC animated:YES completion:nil];
}



//- (UIImagePickerController *)imagePicker
//{
//    if (_imagePicker == nil) {
//        _imagePicker = [[UIImagePickerController alloc] init];
//        _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;    //设置来源为摄像头
//        _imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceRear; //设置使用的摄像头为：后置摄像头
//        if (self.isTakeVedio) {
//            _imagePicker.mediaTypes = @[(NSString *)kUTTypeVideo];    //设置为视频模式注意媒体类型定义在MobileCoreServices.framework中
//            _imagePicker.videoQuality = UIImagePickerControllerQualityTypeIFrame1280x720;   //设置视频质量
//            _imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;  //设置摄像头模式为录制视频
//        }
//        else{
//            _imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto; //设置摄像头模式为拍照
//        }
//    }
//    return _imagePicker;
//}


-(void)openVedioing
{
    VedioingViewController *vedioVC = [[VedioingViewController alloc]init];
    vedioVC.delegate = self;
    [self.superViewController presentViewController:vedioVC animated:YES completion:nil];
    
}

-(void)openVoiceing
{
    VoiceingViewController *voiceVC = [[VoiceingViewController alloc]init];
    voiceVC.delegate = self;
    [self.superViewController presentViewController:voiceVC animated:YES completion:nil];
}


-(void)openLocation
{
    //设置代理主要就是问了获得数据，此处不想用代理，可以使用其他方式获得数据
    UserLocationViewController *userLocationVC = [[UserLocationViewController alloc]init];
//    userLocationVC.delegate = self;
    UINavigationController *navVC = [[UINavigationController alloc]initWithRootViewController:userLocationVC];
    
    [self.superViewController presentViewController:navVC animated:YES completion:nil];
}

/**
 *  获得屏幕上的根控制器, 无用
 *
 *  @return
 */
-(UIViewController *)keyWindowRootViewController
{
    //rootViewController 默认是为nil的
    return  [[UIApplication sharedApplication] keyWindow].rootViewController;
}

#pragma mark textViewDelegate
//开始编辑
-(BOOL)textViewShouldEndEditing:(UITextView *)textView
{
    //设置其他属性都不选中
    self.voiceButton.selected = self.faceButton.selected = self.moreButton.selected = NO;
    
    
    //进行一些初始化处理
    return YES;
}


//内容长度发生变化
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    
//    NSLog(@"---------%@", text);
    
    //对内容进行一些细节处理, 点击的是发送按钮
    if([text isEqualToString:@"\n"]){
        [self sendTextMessage:textView.attributedText];
        return YES;
    }
    
    //说明是点击的删除按钮
    if([text isEqualToString:@""]){
        //判断前面的文字是否是一个表情，
    }
    
    return YES;
}

//本身发生变化
//-(void)textViewDidChange:(UITextView *)textView
//{
//    //本身发生变化的时候进行的一些处理， 更改
//}


#pragma mark UIImagePackerViewControllerDelegate
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    //关闭这个控件
     [self.superViewController dismissViewControllerAnimated:YES completion:nil];
    
    [self showKeyboard:KeyboardShowTypeMore];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [self.superViewController dismissViewControllerAnimated:YES completion:nil];
    
//    UIImage *image = info[UIImagePickerControllerOriginalImage];
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:(NSString *)kUTTypeImage]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        if (self.isAddCustomFaceing) {
            //说明正在添加表情图片
            NSURL *imageUrl = [info objectForKey:UIImagePickerControllerReferenceURL];
            FaceModel *model = [[FaceModel alloc]init];
            model.urlString = imageUrl;
            
            //添加到plist文件中
            [[FileManager sharedFileManager]addCustomFace:model];
            [self showKeyboard:KeyboardShowTypeFace];
        }else{
              [self sendImage:@[image]];
            [self showKeyboard:KeyboardShowTypeMore];
        }
        
    }else if([type isEqualToString:(NSString *)kUTTypeVideo]){
        NSURL *url = [info objectForKey:UIImagePickerControllerMediaURL];
        NSString *urlPath = [url path];
        if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlPath)) {
            UISaveVideoAtPathToSavedPhotosAlbum(urlPath, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
        }
    }
    //显示系统键盘
    
}


- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error) {
        NSLog(@"保存视频过程中发生错误，错误信息:%@",error.localizedDescription);
    }else{
        NSLog(@"视频保存成功.");
        //录制完之后自动播放
        NSURL *url=[NSURL fileURLWithPath:videoPath];
//        _player=[AVPlayer playerWithURL:url];
//        AVPlayerLayer *playerLayer=[AVPlayerLayer playerLayerWithPlayer:_player];
//        playerLayer.frame = self.mImageview.frame;
//        [self.mImageview.layer addSublayer:playerLayer];
//        [_player play];
        
        
        
        //获取一个视频的时间
        
        
        [self sendVodieMessage:url time:0];
    }
}

/**
 *  发送视频
 *
 *  @param url
 */
-(void)sendVodieMessage:(NSURL *)url time:(NSTimeInterval)time
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(chatBar:sendVoideMessage:time:)]) {
        [self.delegate chatBar:self sendVodieMessage:url time:time];
    }
}



#pragma mark 发送事件
-(void)sendTextMessage:(NSAttributedString *)text
{
    if (!text || text.length == 0) {
        return;
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(chatBar:sendMessage:)]) {
        [self.delegate chatBar:self sendMessage:text];
    }
    
    //还没有完呢，需要设置textView的内容为空
    self.textView.attributedText = @"";
}


//发送音频事件
-(void)sendVocieMessage:(NSString *)voiceName time:(NSTimeInterval )time
{
    if(self.delegate && [self.delegate respondsToSelector:@selector(chatBar:sendVoice:time:)])
    {
        [self.delegate chatBar:self sendVoice:voiceName time:time];
    }
    
}

-(void)sendLocation:(CLLocationCoordinate2D) location
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(chatBar:sendLocation:)]) {
        [self.delegate chatBar:self sendLocation:location];
    }
}


-(void)sendImage:(NSArray *)image
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(chatBar:sendPictures:)]) {
        [self.delegate chatBar:self sendPictures:image];
    }
}


#pragma mark VocieControlelr 以及VedioController delegate






/**
 *  textView 添加表情 通过attributedText 来添加表情，
 发送通知的时候中的object是发动通知对象
 selectedRange 控制文字选中位置，当length为0 时，可以用来控制光标的位置
 textView 如果是普通文字，文字大小由textViewFont控制
 如果是attributedText 文字大小是不由font控制的，应该使用addAttribute
 删除的时候可以获得当前的内容，然后删除后再赋值回去，还有系统自带的方法  deletebACKWORD;
 发送带有图片的内容，使用一个方法将表情又转为对应的文字，使用attributedText 的enummerateAttributeInRange方法进行遍历   
 */


@end
